[ -f "$1" ] || { echo "Usage: $0 <file>" && exit 1 ; }
[ -z "$2" ] && echo "Usage: $0 <file> <mirror>, example: $0 <file> registry.cn-hangzhou.aliyuncs.com/registry_mirrors" && exit 1

[ -z "$3" -o -z "$4" ] && echo "Usage: $0 <file> <mirror>, example: $0 <file> registry.cn-hangzhou.aliyuncs.com/registry_mirrors <user> <pass>" && exit 1

images=(
$(grep -Po '(?<=("|:))[^"]+/[^"]+:v\d+.\d+.\d+(@[^"]+)?(?=("|$))' $1 | xargs -n1)
$(grep -Po  '(?<=image:).*' $1 | sort -u)
)

# http proxy
export https_proxy=http://192.168.0.30:7890
# no proxy: vip
export no_proxy=vip.kubernetes.io,aliyuncs.com,192.168.0.100

USERNAME=$3
PASSWORD=$4

declare -a finallyImages
MIRROR=${2:-registry.cn-hangzhou.aliyuncs.com/mageedu_mirrors}
crane auth login ${MIRROR%%/*}   -u $USERNAME -p $PASSWORD
[ $? -eq 0 ] || { echo 'not auth register'; exit 1; }
for image in ${images[*]}; do
{
        image=$(echo $image | tr -d '"')
        suffix=$(echo $image | grep -Po '(?<=/)?[^/]+?(?=(@|$))')
        echo $suffix
        finillayImage=$(echo ${MIRROR}/$suffix | awk '{print $1}')
        finillayImages[${#finillayImages[*]}]=$finillayImage


        crane copy $image $finillayImage
        [ $? -eq 0 ] || { echo 'upload failed....' ; exit 1; }
        echo

        echo "sed replace $image to $finillayImage in $1"
        sed -i "s,$image,$finillayImage,g" $1
        echo
} &
done
wait

echo finally images:
echo ${finillayImages[@]} | xargs -n1
